package threads.threadlocal;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;


/**
 * 使用 InheritableThreadLocal 可以在子线程中取得父线程继承下来的值。
 *
 */
public class InheritableThreadLocalDemo {
    public static InheritableThreadLocal threadLocal = new InheritableThreadLocal();

    public static void main(String[] args) throws InterruptedException {
        for (int i = 0; i < 5; i++) {
            if (threadLocal.get() == null) {
                threadLocal.set("在main线程中放入的值");
            }

            System.out.println("在main线程中取值：" + threadLocal.get());
            TimeUnit.SECONDS.sleep(1);
        }

        ThreadA subThread = new ThreadA();
        subThread.start();
    }
}

class ThreadA extends Thread {

    @SneakyThrows
    @Override
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("在ThreadA线程中取值：" + InheritableThreadLocalDemo.threadLocal.get());
            TimeUnit.SECONDS.sleep(1);
        }
    }

}
